package com.wz.dhs.utils;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.net.url.UrlBuilder;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.Method;
import com.wz.dhs.exception.BusinessException;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

@Slf4j
public class FileUploaderUtils {

    public static void upload(byte[] bytes, String url, String md5,String fileTypeSuffix) throws IOException {
        UrlBuilder urlBuilder = UrlBuilder
                .ofHttp(url, null);
        HttpRequest httpRequest = new HttpRequest(urlBuilder);
        HttpResponse response = httpRequest
                .method(Method.PUT)
                .contentLength(bytes.length)
                .header("Content-MD5", md5)
                .contentType(getContentTypeByFile(fileTypeSuffix))
                .body(bytes)
                .execute();
        // 处理响应
        if (response.isOk()) {
            System.out.println("File uploaded successfully");
        } else {
            log.info("上传文件异常:{}",response);
            System.out.println("Failed to upload file");
            throw new BusinessException("10086");
        }

    }

    public static void uploadAudio(byte[] bytes, String url, String md5) throws IOException {
        UrlBuilder urlBuilder = UrlBuilder
                .ofHttp(url, null);
        HttpRequest httpRequest = new HttpRequest(urlBuilder);
        HttpResponse response = httpRequest
                .method(Method.PUT)
                .contentLength(bytes.length)
                .contentType("application/octet-stream")
                .body(bytes)
                .execute();
        // 处理响应
        if (response.isOk()) {
            System.out.println("File uploaded successfully");
        } else {
            log.info("上传文件异常:{}",response);
            System.out.println("Failed to upload file");
            throw new BusinessException("10086");
        }

    }

    private static String getContentTypeByFile(String fileSuffix){
        String contentType = null;
        switch (fileSuffix.toUpperCase()){
            case "JPEG" :
            case "JPG" :
                contentType = "image/jpeg";
                break;
            case "PNG":
                contentType = "image/png";
                break;
            case "MP4":
                contentType = "video/mp4";
                break;
            case "MP3":
                contentType = "audio/mp3";
                break;
            case "WAV":
                contentType = "audio/wav";
                break;
            case "AAC":
                contentType = "audio/aac";
                break;
            case "WEBM":
                contentType = "application/octet-stream";
                break;
            case "PPT":
            case "PPTX":
                contentType = "application/octet-stream";
                break;
            default:
                throw new BusinessException("10087");
        }
        return contentType;
    }

    /**
     * 获取文件的MD5值大小
     *
     * @return
     */
    public static byte[] getMD5(byte[] bytes) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(bytes, 0, bytes.length);
            return md5.digest();
        } catch (Exception e) {
            log.error("file{} MD5 fail", e);
            return null;
        } finally {

        }
    }

    private static final int BUFFER_SIZE = 1024;

    @SneakyThrows
    public static String getFileMd5(File file) {
        if (file == null || !file.isFile()) {
            return null;
        }
        MessageDigest digest;
        FileInputStream in;
        byte[] buffer = new byte[BUFFER_SIZE];
        int len;
        try {
            digest = MessageDigest.getInstance("MD5");
            in = new FileInputStream(file);
            while ((len = in.read(buffer, 0, BUFFER_SIZE)) != -1) {
                digest.update(buffer, 0, len);
            }
            in.close();
        } catch (IOException | NoSuchAlgorithmException e) {
            System.out.println(e.getMessage());
            return null;
        }
        return Base64.encode(digest.digest());
    }


    public static void main(String[] args) {
        String fileMd5 = getFileMd5(new File("D:\\Download\\goole\\a068a48c2e89f0ed839072d918646dd6.mp4"));
        System.out.println(fileMd5);
    }


}
